<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/jexo/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/jexo/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/jexo/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/jexo/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/jexo/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/jexo/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/jexo/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Android,封装," />










<meta name="description" content="如果对 Retrofit2+RxJava 封装还不是很了解的话可以参考下:http://www.jianshu.com/p/17e3e3102c1f如果对Dagger2 还不是很了解,可以参考下:http://www.jianshu.com/p/cd2c1c9f68d4如果对mvp还不是很了解,可以自己百度下,很多的,我就不贴出了.">
<meta name="keywords" content="Android,封装">
<meta property="og:type" content="article">
<meta property="og:title" content="Retrofit2-RxJava-Dagger2-MVP完美封装">
<meta property="og:url" content="http://ja_project.gitee.io/jexo/2018/04/18/Retrofit2-RxJava-Dagger2-MVP完美封装/index.html">
<meta property="og:site_name" content="Ling Hu Blog">
<meta property="og:description" content="如果对 Retrofit2+RxJava 封装还不是很了解的话可以参考下:http://www.jianshu.com/p/17e3e3102c1f如果对Dagger2 还不是很了解,可以参考下:http://www.jianshu.com/p/cd2c1c9f68d4如果对mvp还不是很了解,可以自己百度下,很多的,我就不贴出了.">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-04-18T13:20:47.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Retrofit2-RxJava-Dagger2-MVP完美封装">
<meta name="twitter:description" content="如果对 Retrofit2+RxJava 封装还不是很了解的话可以参考下:http://www.jianshu.com/p/17e3e3102c1f如果对Dagger2 还不是很了解,可以参考下:http://www.jianshu.com/p/cd2c1c9f68d4如果对mvp还不是很了解,可以自己百度下,很多的,我就不贴出了.">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/jexo/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://ja_project.gitee.io/jexo/2018/04/18/Retrofit2-RxJava-Dagger2-MVP完美封装/"/>





  <title>Retrofit2-RxJava-Dagger2-MVP完美封装 | Ling Hu Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?abc8796c232e2b898d516245257842b4";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/jexo/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Ling Hu Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/jexo/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/jexo/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/jexo/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/jexo/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/jexo/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://ja_project.gitee.io/jexo/jexo/2018/04/18/Retrofit2-RxJava-Dagger2-MVP完美封装/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Ling Hu">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/jexo/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Ling Hu Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Retrofit2-RxJava-Dagger2-MVP完美封装</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-04-18T20:52:23+08:00">
                2018-04-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/jexo/categories/完美封装/" itemprop="url" rel="index">
                    <span itemprop="name">完美封装</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/jexo/2018/04/18/Retrofit2-RxJava-Dagger2-MVP完美封装/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count gitment-comments-count" data-xid="/jexo/2018/04/18/Retrofit2-RxJava-Dagger2-MVP完美封装/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>如果对 Retrofit2+RxJava 封装还不是很了解的话<br>可以参考下:<br><a href="http://www.jianshu.com/p/17e3e3102c1f" target="_blank" rel="noopener">http://www.jianshu.com/p/17e3e3102c1f</a><br>如果对Dagger2 还不是很了解,可以参考下:<br><a href="http://www.jianshu.com/p/cd2c1c9f68d4" target="_blank" rel="noopener">http://www.jianshu.com/p/cd2c1c9f68d4</a><br>如果对mvp还不是很了解,可以自己百度下,很多的,我就不贴出了.</p>
<a id="more"></a>
<p>下面我简单讲述下:<br>请先看下目录结构:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">com</span><br><span class="line">└── javalong</span><br><span class="line">└── rrdm</span><br><span class="line">├── activity</span><br><span class="line">│   ├── component</span><br><span class="line">│   │   ├── LoginActivityComponent.java</span><br><span class="line">│   │   └── MainActivityComponent.java</span><br><span class="line">│   ├── iview</span><br><span class="line">│   │   ├── ILoginView.java</span><br><span class="line">│   │   └── IMainView.java</span><br><span class="line">│   ├── LoginActivity.java</span><br><span class="line">│   ├── MainActivity.java</span><br><span class="line">│   ├── module</span><br><span class="line">│   │   ├── LoginActivityModule.java</span><br><span class="line">│   │   └── MainActivityModule.java</span><br><span class="line">│   └── presenter</span><br><span class="line">│       ├── LoginPresenter.java</span><br><span class="line">│       └── MainPresenter.java</span><br><span class="line">├── app</span><br><span class="line">│   ├── annotation</span><br><span class="line">│   │   └── ActivityScope.java</span><br><span class="line">│   ├── AppBaseActivity.java</span><br><span class="line">│   ├── AppBaseApplication.java</span><br><span class="line">│   ├── component</span><br><span class="line">│   │   └── AppComponent.java</span><br><span class="line">│   ├── iview</span><br><span class="line">│   │   └── MvpView.java</span><br><span class="line">│   ├── module</span><br><span class="line">│   │   └── AppModule.java</span><br><span class="line">│   └── presenter</span><br><span class="line">│       └── AppPresenter.java</span><br><span class="line">└── retrofit</span><br><span class="line">├── ResponseMessageBean.java</span><br><span class="line">├── RetrofitHelper.java</span><br><span class="line">├── ServerApi.java</span><br><span class="line">├── TWGsonConverterFactory.java</span><br><span class="line">├── TWGsonRequestBodyConverter.java</span><br><span class="line">├── TWGsonResponseBodyConverter.java</span><br><span class="line">└── TWJavaCallAdapterFactory.java</span><br></pre></td></tr></table></figure>
<p>这里我就不对mvp,dagger2和Retrofit2+Rxjava过多介绍了.这里就介绍下具体的封装.<br>我这里是一个Presenter和一个Activity(View)相互对应,所以我让Presenter直接在基类中注入.对其进行统一管理:<br>AppPresenter.<a href="http://lib.csdn.net/base/javase" target="_blank" rel="noopener">Java</a>:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">/** </span><br><span class="line"> * Created by javalong on 16-12-27. </span><br><span class="line"> * presenter基类 </span><br><span class="line"> */  </span><br><span class="line">public abstract class AppPresenter&lt;V extends MvpView&gt;&#123;  </span><br><span class="line">    @Inject  </span><br><span class="line">    protected V mvpView;  </span><br><span class="line">  </span><br><span class="line">    public AppPresenter(V mvpView) &#123;  </span><br><span class="line">        this.mvpView = mvpView;  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    public abstract void attach();  </span><br><span class="line">    public abstract void detach();  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>AppBaseActivity.java—&gt;所有Activity的基类,对presenter进行统一处理.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">/** </span><br><span class="line"> * Created by javalong on 16-12-27. </span><br><span class="line"> */  </span><br><span class="line">  </span><br><span class="line">public abstract class AppBaseActivity&lt;T extends AppPresenter&gt; extends AppCompatActivity &#123;  </span><br><span class="line">    @Inject  </span><br><span class="line">    protected T mPresenter;  </span><br><span class="line">  </span><br><span class="line">    @Override  </span><br><span class="line">    protected void onCreate(@Nullable Bundle savedInstanceState) &#123;  </span><br><span class="line">        super.onCreate(savedInstanceState);  </span><br><span class="line">        initInjects();  </span><br><span class="line">        mPresenter.attach();  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    protected abstract void initInjects();  </span><br><span class="line">  </span><br><span class="line">    @Override  </span><br><span class="line">    protected void onDestroy() &#123;  </span><br><span class="line">        super.onDestroy();  </span><br><span class="line">        mPresenter.detach();  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    protected AppComponent getAppComponent()&#123;  </span><br><span class="line">        return AppBaseApplication.getInstance().getAppComponent();  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>AppBaseActivity中引用了AppComponent.这个需要在AppBaseApplication进行初始化.Component是dagger2依赖注入的基础.</p>
<p>AppBaseApplication.java</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">/** </span><br><span class="line"> * Created by javalong on 16-12-27. </span><br><span class="line"> */  </span><br><span class="line">  </span><br><span class="line">public class AppBaseApplication extends Application &#123;  </span><br><span class="line">  </span><br><span class="line">    private static AppBaseApplication instance;  </span><br><span class="line">  </span><br><span class="line">    public static AppBaseApplication getInstance() &#123;  </span><br><span class="line">        return instance;  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    AppComponent appComponent;  </span><br><span class="line">  </span><br><span class="line">    public AppComponent getAppComponent() &#123;  </span><br><span class="line">        return appComponent;  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    @Override  </span><br><span class="line">    public void onCreate() &#123;  </span><br><span class="line">        super.onCreate();  </span><br><span class="line">        instance = this;  </span><br><span class="line">        if (appComponent == null) &#123;  </span><br><span class="line">            appComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build();  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果不熟悉Dagger2的童鞋,可能会发现没有<code>DaggerAppComponent</code>这个类,不要慌,请’Make Project’编译下项目.<code>DaggerAppComponent</code>会自动生成.<code>DaggerAppComponent</code>其实是根据我们写的<code>AppComponent</code>接口生成的一个类,下面我们先看下AppComponent.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">@Singleton  </span><br><span class="line">@Component(modules = AppModule.class)  </span><br><span class="line">public interface AppComponent &#123;  </span><br><span class="line">    Context getContext();  </span><br><span class="line">    ServerApi getServerApi();  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>AppComponent这个接口其实很简单.这里记得要加上<code>@Scope</code>注解(@Singleton是@Scope的一种)使Component和Module中provide出来的对象联系起来.<br>关于@Scope注解的含义我这里就不过多介绍了,大家可以参考我上面推荐的文章.写的很不错.<br>接下来看下AppModule中提供了哪些依赖</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">@Module  </span><br><span class="line">public class AppModule &#123;  </span><br><span class="line">  </span><br><span class="line">    private Context mContext;  </span><br><span class="line">  </span><br><span class="line">    public AppModule(Context context) &#123;  </span><br><span class="line">        this.mContext = context;  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    @Provides @Singleton  </span><br><span class="line">    Context provideContext()&#123;  </span><br><span class="line">        return mContext;  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    @Provides @Singleton  </span><br><span class="line">    ServerApi provideServerApi(Context context)&#123;  </span><br><span class="line">        RetrofitHelper.init(context);  </span><br><span class="line">        return RetrofitHelper.getApi();  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里的@Singleton 和前面AppComponent的@Singleton 相互连接,让我们造成了单例的假象.其实@Singleton并没有单例的作用,是因为<br>和AppComponent一起使用,AppComponent只创建了一次,所以产生’单例’这个现象.(我这里又重复得说了一边,汗~~)<br>AppComponent和AppModule请根据自己项目的详细情况来进行封装,由于我这个demo比较简单,所以只@Provides 了2个对象出来.</p>
<p>下面我来详细介绍下Activity和Presenter之间的封装.<br>首先我这里先说明下,我这里的一个Activity,对应着1个view,1个presenter,1个component,1个module.<br>可能封装的不是很好,没有领悟到mvp的精髓,但是对我来说更加清晰.<br>MainActivity.java</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">public class MainActivity extends AppBaseActivity&lt;MainPresenter&gt; implements IMainView&#123;  </span><br><span class="line">  </span><br><span class="line">    @Override  </span><br><span class="line">    protected void onCreate(Bundle savedInstanceState) &#123;  </span><br><span class="line">        super.onCreate(savedInstanceState);  </span><br><span class="line">        setContentView(R.layout.activity_main);  </span><br><span class="line">        mPresenter.test();  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    @Override  </span><br><span class="line">    protected void initInjects() &#123;  </span><br><span class="line">        DaggerMainActivityComponent.builder()  </span><br><span class="line">                .appComponent(getAppComponent())  </span><br><span class="line">                .mainActivityModule(new MainActivityModule(this))  </span><br><span class="line">                .build()  </span><br><span class="line">                .inject(this);  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">    @Override  </span><br><span class="line">    public void showMainMessage() &#123;  </span><br><span class="line">        ((TextView)findViewById(R.id.tv_test))  </span><br><span class="line">                .setText(&quot;你好 dagger&quot;);  </span><br><span class="line">        findViewById(R.id.bt_login)  </span><br><span class="line">        .setOnClickListener(new View.OnClickListener() &#123;  </span><br><span class="line">            @Override  </span><br><span class="line">            public void onClick(View v) &#123;  </span><br><span class="line">                LoginActivity.start(MainActivity.this);  </span><br><span class="line">                MainActivity.this.finish();  </span><br><span class="line">            &#125;  </span><br><span class="line">        &#125;);  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>MainActivity必须继承AppBaseActivity,然后传入泛型,即对应的Presenter的类型.在initInjects中必须完成Dagger2的注入操作,因为在AppBaseActivity中的Presenter需要<br>注入,如果不注入,在基类中调用mPresenter.attach会出错.<br>当你使用Dagger2的时候,其实很明显会暴露他的一个缺点,必须要编译后,才能产生对应的Dagger**Component.当然相对于他的好处来讲,这点还是可以忍受的.<br>前面提到了必须要对基类中的Presenter进行注入,那么到底注入的是什么呢?这里我以MainPresenter为例.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">public class MainPresenter extends AppPresenter&lt;IMainView&gt;&#123;  </span><br><span class="line">  </span><br><span class="line">    @Inject  </span><br><span class="line">    public MainPresenter(IMainView mvpView) &#123;  </span><br><span class="line">        super(mvpView);  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    @Override  </span><br><span class="line">    public void attach() &#123;  </span><br><span class="line">  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    @Override  </span><br><span class="line">    public void detach() &#123;  </span><br><span class="line">  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    public void test() &#123;  </span><br><span class="line">        mvpView.showMainMessage();  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>MainActivityModule.java<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">@Module  </span><br><span class="line">public class MainActivityModule  &#123;  </span><br><span class="line">  </span><br><span class="line">    private IMainView mainView;  </span><br><span class="line">  </span><br><span class="line">    public MainActivityModule(IMainView mainView) &#123;  </span><br><span class="line">        this.mainView = mainView;  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    @Provides @ActivityScope IMainView provideIMainView()&#123;  </span><br><span class="line">        return mainView;  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    /** </span><br><span class="line">     * 这种方式,和直接在MainPresenter构造方法上添加@Inject是一样的 </span><br><span class="line">     * 二选一即可. </span><br><span class="line">     */  </span><br><span class="line">//    @Provides @ActivityScope MainPresenter provideMainPresenter(IMainView mainView)&#123;  </span><br><span class="line">//        return new MainPresenter(mainView);  </span><br><span class="line">//    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>看注释,这里有2种方式可以完成MainPresenter的注入,一种是直接在MainPreenter的构造方法上加上@Inject,一种是在对应的Module中使用<br>@Provides 把MainPresenter提供出来. 至于@ActivityScope其实是和前面@Scope一样的,我这里就不过多介绍了.<br>最关键的一步:<br>MainActivityComponent.java</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">@ActivityScope  </span><br><span class="line">@Component(dependencies = AppComponent.class,modules = MainActivityModule.class)  </span><br><span class="line">public interface MainActivityComponent&#123;  </span><br><span class="line">    /** </span><br><span class="line">     * @param mainView </span><br><span class="line">     * 这里必须使用MainActivity,不能使用IMain接口 </span><br><span class="line">     * 否则会造成@Inject注入失败 </span><br><span class="line">     */  </span><br><span class="line">    void inject(MainActivity mainView);  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>必须在对应的Component提供注入方法(名字不一定叫inject).<br>MainActivity.java 部分代码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@Override  </span><br><span class="line">   protected void initInjects() &#123;  </span><br><span class="line">       DaggerMainActivityComponent.builder()  </span><br><span class="line">               .appComponent(getAppComponent())  </span><br><span class="line">               .mainActivityModule(new MainActivityModule(this))  </span><br><span class="line">               .build()  </span><br><span class="line">               .inject(this);  </span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<p>这样才完成了注入.<br>在<code>DaggerMainActivityComponent</code>中会先对AppBaseActivity进行注入,然后再对MainActivity进行注入.<br>这里我简单的讲述了封装,如果还有什么不懂的地方可以再交流~~~github: <a href="https://github.com/javalong/Retrofit2-RxJava-Dagger2-MVP" target="_blank" rel="noopener">https://github.com/javalong/Retrofit2-RxJava-Dagger2-MVP</a></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>Donate comment here</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/jexo/images/wechatpay.png" alt="Ling Hu 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/jexo/images/alipay.png" alt="Ling Hu 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/jexo/tags/Android/" rel="tag"># Android</a>
          
            <a href="/jexo/tags/封装/" rel="tag"># 封装</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/jexo/2018/04/18/hello-world/" rel="next" title="新的起点，新的征程">
                <i class="fa fa-chevron-left"></i> 新的起点，新的征程
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/jexo/2018/04/18/Retrofit+RxJava完美封装/" rel="prev" title="Retrofit+RxJava完美封装">
                Retrofit+RxJava完美封装 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      
        <div id="gitment-container"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/jexo/images/avatar.jpg"
                alt="Ling Hu" />
            
              <p class="site-author-name" itemprop="name">Ling Hu</p>
              <p class="site-description motion-element" itemprop="description">Android,源码解析,每天进步一点点</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/jexo/archives/">
              
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/jexo/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/jexo/tags/index.html">
                  <span class="site-state-item-count">14</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/javalong" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ling Hu</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/jexo/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/jexo/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/jexo/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/jexo/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/jexo/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/jexo/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  







<!-- LOCAL: You can save these files to your site and update links -->
    
        
        <link rel="stylesheet" href="https://aimingoo.github.io/gitmint/style/default.css">
        <script src="https://aimingoo.github.io/gitmint/dist/gitmint.browser.js"></script>
    
<!-- END LOCAL -->

    
      <style>
        a.gitment-editor-footer-tip { display: none; }
        .gitment-container.gitment-footer-container { display: none; }
      </style>
    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitmint({
            id: getId(),
            owner: 'javalong',
            repo: 'RxJava-Operator',
            
            lang: "zh-Hans" || navigator.language || navigator.systemLanguage || navigator.userLanguage,
            
            oauth: {
            
            
                client_secret: '06b042e57b8420f5002a6407348dde078bcde761',
            
                client_id: '1b5481d6512b2f28d7a2'
            }});
        gitment.render('gitment-container');
      }

      function getId(){
            if( window.location.pathname.length>=50){
                return window.location.pathname.substr(0,50)
            }else{
                return window.location.pathname
            }
      }

      
      renderGitment();
      
      </script>
    







  





  

  

  

  
  

  

  

  

</body>
</html>
